package com.lx.service.impl;

import com.lx.dao.NewsDao;
import com.lx.dao.NewsEsRepository;
import com.lx.entity.News;
import com.lx.service.NewsService;
import com.lx.util.PageInfo;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class NewsServiceImpl implements NewsService {

    @Autowired
    NewsDao newsDao;
    @Autowired
    ElasticsearchRestTemplate esTemplate;
    @Autowired
    NewsEsRepository newsEsRepository;


    @Override
    public List<News> getAllNews() {
        return newsDao.selectAll();
    }

    @Override
    public PageInfo<News> getPageInfo(Map<String, Object> params) {

        PageInfo<News> pageInfo=new PageInfo<>();
        int pageNum=Integer.parseInt(params.get("pageNum").toString());
        int pageSize=Integer.parseInt(params.get("pageSize").toString());
        NativeSearchQueryBuilder queryBuilder=new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if(params.containsKey("title")){
            boolQueryBuilder.must(QueryBuilders.matchQuery("title", params.get("title")));

        }
        // 创建时间查询 - 只使用年月日
        if (params.containsKey("createTime") && params.get("createTime") != null) {
            String createTimeStr = params.get("createTime").toString();
            if (!createTimeStr.isEmpty()) {
                try {

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date date = sdf.parse(createTimeStr);

                    String esDateStr = sdf.format(date);
                    boolQueryBuilder.must(QueryBuilders.termQuery("createTime", esDateStr));
                } catch (ParseException e) {
                    // 如果日期解析失败，使用 match 查询
                    boolQueryBuilder.must(QueryBuilders.matchQuery("createTime", createTimeStr));
                }
            }
        }
        queryBuilder.withQuery(boolQueryBuilder);

        queryBuilder.withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC));


        //高亮
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        highlightBuilder.field("title")
                .preTags("<span style='color:red'>")
                .postTags("</span>");
        queryBuilder.withHighlightBuilder(highlightBuilder);
        queryBuilder.withPageable(PageRequest.of((pageNum - 1), pageSize));



        //结果高亮
        SearchHits<News> hits=esTemplate.search(queryBuilder.build(), News.class);
        List<News> newsList=new ArrayList<>(pageSize+5);
        for(SearchHit<News> hit :hits.getSearchHits()){
            News news= hit.getContent();
            Map<String, List<String>> highLightMap = hit.getHighlightFields();
            if(!highLightMap.isEmpty()){
                // 处理 title 高亮
                List<String> titleList = highLightMap.get("title");
                if (titleList != null && !titleList.isEmpty()) {
                    news.setTitle(titleList.get(0));
                }

                // 处理 createTime 高亮
//                List<String> createTimeList = highLightMap.get("createTime");
//                if (createTimeList != null && !createTimeList.isEmpty()) {
//                    String highlightedCreateTime = createTimeList.get(0);
//                    // 去除HTML标签
//                    String cleanDate = highlightedCreateTime.replaceAll("<[^>]*>", "");
//                    try {
//                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//                        Date date = dateFormat.parse(cleanDate);
//                        news.setCreateTime(date);
//                    } catch (ParseException e) {
//                        // 解析失败时使用原始值或记录日志
//                        // 可以选择不设置该字段，保持原始值
//                    }
//                }
            }
            newsList.add(news);
        }
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotalCount((int) hits.getTotalHits());
        pageInfo.setList(newsList);
        return pageInfo;
    }

    @Override
    public News selectById(int id) {
        return newsDao.selectById(id);
    }

    @Override
    public News getNewsByTitle(String title) {
        return newsDao.selectNewsByTitle(title);
    }

    @Override
    public boolean addNews(News news) {
        return newsDao.addNews(news) == 1;
    }

    @Override
    public boolean updateNews(News news) {
        return newsDao.updateNews(news)>0;
    }

    @Override
    public boolean delNews(int id) {
        return newsDao.delNews(id)>0;
    }
}
